<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/10/21
 * Time: 下午4:21
 */

namespace App\Http\Controllers\Admin;

use App\Models;
use App\Repositories;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleController extends AdminController
{

    public function __construct()
    {
        parent::__construct();

        $this->setTemplatePrefix(config('admin.systems.template_prefix', 'admin.').'role.');
    }

    /**
     * 获取当前控制器服务仓库对象
     * @return mixed
     */
    public function getServiceRepository() : Repositories\Admin\RoleRepository
    {
        if (!($this->serviceRepository instanceof Repositories\Admin\RoleRepository)) {
            $this->serviceRepository = new Repositories\Admin\RoleRepository();
        }

        return $this->serviceRepository;
    }

    /**
     * 角色列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $data = $this->getServiceRepository()->getPaginateData();

        return $this->fetch('index', ['data'=>$data]);
    }

    /**
     * 更新角色信息
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function edit(Request $request)
    {
        if (strtolower($request->method()) !== 'post') {
            $id = $request->route('id', 0);

            $detail = $this->getServiceRepository()->getSelectModel();
            $action = 'add';
            if (!empty($id)) {
                $detail = $this->getServiceRepository()->getDetailById($id);
                $action = 'edit';
            }

            return $this->fetch('edit', [
                'metaTitle' => '更新角色信息',
                'postUrl'   => get_admin_url('role/edit'),
                'detail'    => $detail,
                'action'    => $action
            ]);
        }

        $info = $request->input('info', []);

        $action = $request->input('action', 'add');

        $this->getServiceRepository()->save($info, $action);

        return $this->success('保存成功');
    }

    /**
     * 权限设置
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function permission(Request $request)
    {
        $roleId = $request->route('role_id', 0);

        if (strtolower($request->method()) !== 'post') {
            $MenuRepository = new Repositories\Admin\MenuRepository();
            $isDeveloper = $roleId == 1 ? null : 0;
            $menuList = $MenuRepository->getMenusList(null, null, $isDeveloper)->toArray();

            //  根据角色编号获取该角色拥有的权限
            $permissionIdList = DB::table('admin_permission_role')->where('role_id', $roleId)->pluck('permission_id')->toArray();

            $permissionNameList = DB::table('admin_permissions')->whereIn('id', $permissionIdList)->pluck('name')->toArray();

            $useMenuList = $MenuRepository->getMenusListBySlugList($permissionNameList);

            $useList = [];
            foreach ($useMenuList as $key=>$value) {
                $useList[$key] = $value['name'];
            }
            return $this->fetch('permission', [
                'metaTitle' => '设置角色权限',
                'postUrl'   => get_admin_url('role/permission', ['role_id'=>$roleId]),
                'menuList'  => list_to_tree($menuList),
                'useList'   => $useList,
                'roleId'    => $roleId
            ]);
        }

        $roleModel = Models\Admin\Role::find($roleId);

        $permissionList = $request->input('permissionList', []);

        $permissionList = array_values(array_filter($permissionList));

        $permissionIds = DB::table('admin_permissions')->whereIn('name', $permissionList)->pluck('id')->toArray();

        $roleModel->perms()->sync($permissionIds);

        return $this->success('权限设置成功');
    }
}